package com.flyou.ccnucenter.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.ResideMenu.ResideMenu;
import com.flyou.ccnucenter.ResideMenu.ResideMenuItem;
import com.flyou.ccnucenter.ui.activity.aboutActivity.AboutWebViewActivity;
import com.flyou.ccnucenter.ui.activity.henuBeside.HenuBesideActivity;
import com.flyou.ccnucenter.ui.activity.mine.PersonalCenterActivity;
import com.flyou.ccnucenter.ui.frgment.HenuImageFragment;
import com.flyou.ccnucenter.ui.frgment.SchoolMEssageFragment;
import com.flyou.ccnucenter.ui.frgment.SchoolNewFragment;
import com.flyou.ccnucenter.ui.frgment.DepartmentNewFragment;
import com.flyou.ccnucenter.utils.SPUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengUpdateAgent;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static String HENU_MEIWEN = "http://mp.weixin.qq.com/mp/homepage?__biz=MzA4MjUyMjYxMA==&hid=1&sn=cf7cada1b10501dc2b8aca495eeb5a2d#wechat_redirect";
    private long exitTime = 0l;
    private ResideMenu resideMenu;
    private MainActivity mContext;
    private ResideMenuItem schoolNew;
    private ResideMenuItem departmentNew;
    private ResideMenuItem schoolBeside;
    private ResideMenuItem weiChat;
    private ResideMenuItem henuImage;
    private ResideMenuItem beside;
    private TextView main_title;
    private SimpleDraweeView title_bar_right_mine;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener;

    /**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushAgent.getInstance(MainActivity.this).onAppStart();
        //    自动更新
        boolean isAutoUpdate = (boolean) SPUtils.get(MainActivity.this, Constant.IS_AUTO_UPDATE, true);
        if (isAutoUpdate) {
            UmengUpdateAgent.silentUpdate(this);// 静默下载
        }
        //    消息推送
        PushAgent mPushAgent = PushAgent.getInstance(MainActivity.this);
        boolean isPushOn = (boolean) SPUtils.get(MainActivity.this, Constant.IS_AUTO_PUSH, true);
        if (isPushOn) {
            mPushAgent.enable();
        } else {
            mPushAgent.disable();
        }
//        支付
//        BP.init(MainActivity.this, "04b2c8d5f1600fc7828b26b86e77faa9");
        setContentView(R.layout.main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

        }
        EventBus.getDefault().register(this);
        mContext = this;
        main_title = (TextView) findViewById(R.id.title_bar_title);
        title_bar_right_mine = (SimpleDraweeView) findViewById(R.id.title_bar_right_mine);
        setHeadImage();
        setUpMenu();



        if (savedInstanceState == null)
            changeFragment(new SchoolNewFragment());

    /*
    *百度地图定位
    * */
        mLocationClient = new LocationClient(getApplicationContext());     //
        myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        mLocationClient.start();

    }



    /*
    * 设置头像
    * */
    private void setHeadImage() {
        String headImage = (String) SPUtils.get(MainActivity.this, "headImage", "");
        title_bar_right_mine.setImageURI(Uri.parse(headImage));
    }

    private void setUpMenu() {
        // attach to current activity;
        resideMenu = new ResideMenu(this);
        resideMenu.setFitsSystemWindows(true);
        resideMenu.setUse3D(false);
        resideMenu.setBackground(R.drawable.menu_background);
        resideMenu.attachToActivity(this);
        resideMenu.setMenuListener(menuListener);
        //valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip. 
        resideMenu.setScaleValue(0.65f);
        resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
        // create menu items;
        schoolNew = new ResideMenuItem(this, R.drawable.icon_home, "校园新闻");
        departmentNew = new ResideMenuItem(this, R.drawable.icon_departemt, "院系新闻");
        schoolBeside = new ResideMenuItem(this, R.drawable.icon_school_beside, "校园公告");
        henuImage = new ResideMenuItem(this, R.drawable.icon_henu_image, "图说Star");
        weiChat = new ResideMenuItem(this, R.drawable.icon_weixin, "Star美文");
        beside = new ResideMenuItem(this, R.drawable.icon_office, "Star周边");

        henuImage.setOnClickListener(this);
        schoolNew.setOnClickListener(this);
        departmentNew.setOnClickListener(this);
        schoolBeside.setOnClickListener(this);
        weiChat.setOnClickListener(this);
        beside.setOnClickListener(this);
        resideMenu.addMenuItem(schoolNew, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(schoolBeside, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(departmentNew, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(weiChat, ResideMenu.DIRECTION_LEFT);
//        resideMenu.addMenuItem(henuImage, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(beside, ResideMenu.DIRECTION_LEFT);
        //   设置打开菜单
        findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
            }
        });
        findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
            }
        });
//        点击判断是否登录
        findViewById(R.id.title_bar_right_mine).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, PersonalCenterActivity.class);
                startActivity(intent);
            }
        });
    }

    //消费点击事件
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        return resideMenu.dispatchTouchEvent(ev);
    }

    @Override
    public void onClick(View view) {
        if (view == schoolNew) {
            changeFragment(new SchoolNewFragment());
            main_title.setText("校园新闻");
        } else if (view == departmentNew) {
            main_title.setText("院系新闻");
            changeFragment(new DepartmentNewFragment());
        } else if (view == schoolBeside) {
            main_title.setText("校园公告");
            changeFragment(new SchoolMEssageFragment());
        } else if (view == weiChat) {
            main_title.setText("Star美文");
//            changeFragment(new WeiChatFragment());
            Intent intent = new Intent(MainActivity.this, AboutWebViewActivity.class);
            intent.putExtra("url", HENU_MEIWEN);
            intent.putExtra("title", "Star美文");
            startActivity(intent);
        } else if (view == henuImage) {
            main_title.setText("图说Star");
            changeFragment(new HenuImageFragment());
        } else if (view == beside) {
            Intent intent = new Intent(MainActivity.this, HenuBesideActivity.class);
            startActivity(intent);
        }
        resideMenu.closeMenu();
    }

    private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
        @Override
        public void openMenu() {
//            Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void closeMenu() {
//            Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
        }
    };

    //切换fragment的操作
    private void changeFragment(Fragment targetFragment) {
        resideMenu.clearIgnoredViewList();

        getSupportFragmentManager()
                .beginTransaction()

                .replace(R.id.main_fragment, targetFragment, "fragment")
                .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)

                .commit();
    }

    // What good method is to access resideMenu？
    public ResideMenu getResideMenu() {
        return resideMenu;
    }

    @Override
    protected void onDestroy() {
        MobclickAgent.onPause(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscriber(tag = Constant.ENABLE_MENU)
    public void enableMenu(String tag) {
        resideMenu.setSwipeDirectioEnable(ResideMenu.DIRECTION_LEFT);


    }

    @Subscriber(tag = Constant.UPDATE_HEADIMAGE)
    public void updateImage(String tag) {
        setHeadImage();


    }

    @Subscriber(tag = Constant.DISABLE_MENU)
    public void disEnableMenu(String tag) {
        resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);


    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次返回键回到桌面", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            System.exit(0);
        }
    }
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            double latitude = bdLocation.getLatitude();
            double longitude = bdLocation.getLongitude();
            SPUtils.put(MainActivity.this,"latitude",String.valueOf(latitude));
            SPUtils.put(MainActivity.this,"longitude",String.valueOf(longitude));
        }
    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }
}
